package cn.zbacm.api.security.service;

import cn.zbacm.api.security.CustomUser;
import cn.zbacm.api.user.entity.User;
import cn.zbacm.api.user.repository.UserRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Optional;

import static org.springframework.security.core.authority.AuthorityUtils.createAuthorityList;

@Slf4j
@Service
public class CustomUserDetailsService implements UserDetailsService {
  @Autowired
  private UserRepository userRepository;

  @Override
  public UserDetails loadUserByUsername(String phoneOrUsername) throws UsernameNotFoundException {
    log.info("start to loadUserByUsername: {}", phoneOrUsername);
    Optional<User> optionalUser =
            userRepository.findByPhoneOrUsername(phoneOrUsername, phoneOrUsername);
    if (optionalUser.isEmpty()) {
      log.info("user not found with login id: " + phoneOrUsername);
      throw new UsernameNotFoundException("user not found with login id: " + phoneOrUsername);
    }

    User user = optionalUser.get();
    log.info("got user id: {}", user.getId());
    return new CustomUser(user.getUsername(), user.getPassword(), createAuthorityList(), user);
  }

  public UserDetails loadUserById(int id) throws UsernameNotFoundException {
    log.info("start to loadUserById: {}", id);
    Optional<User> optionalUser = userRepository.findById(id);
    if (optionalUser.isEmpty()) {
      log.info("user not found with id: " + id);
      throw new UsernameNotFoundException("user not found with id: " + id);
    }

    User user = optionalUser.get();
    log.info("got user id: {}", user.getId());
    return new CustomUser(user.getUsername(), user.getPassword(), createAuthorityList(), user);
  }
}
